package com.kkb.merchant.center.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kkb.merchant.center.common.pojo.UserInfo;
import com.kkb.merchant.center.common.util.JwtUtil;
import com.kkb.merchant.center.common.util.ResultEnum;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

public class JWTLoginFilter extends UsernamePasswordAuthenticationFilter {

    private AuthenticationManager authenticationManager;

    public JWTLoginFilter(AuthenticationManager authenticationManager){
        this.authenticationManager = authenticationManager;
    }


    /**
     * 校验用户登录的用户名和密码是否匹配
     * @param request
     * @param response
     * @return
     * @throws AuthenticationException
     */
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        try {
            UserInfo userInfo = new ObjectMapper().readValue(request.getInputStream(),UserInfo.class);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken
                    = new UsernamePasswordAuthenticationToken(userInfo.getUserName(),userInfo.getUserPassword(),new ArrayList<>());

            Authentication authentication = this.authenticationManager.authenticate(usernamePasswordAuthenticationToken);
            return authentication;
        } catch (IOException e) {
            throw new RuntimeException();
        }
    }

    /**
     * 如果登录成功，则返回客户端Token
     * @param request
     * @param response
     * @param chain
     * @param authResult
     * @throws IOException
     * @throws ServletException
     */
    @Override
    protected void successfulAuthentication(HttpServletRequest request,
                                            HttpServletResponse response, FilterChain chain, Authentication authResult)
            throws IOException, ServletException {
        Calendar calendar = Calendar.getInstance();
        Date now = calendar.getTime(); //签发时间
        calendar.setTime(new Date());
        calendar.add(Calendar.MINUTE,60);
        Date expireTime =calendar.getTime(); //过期时间
        String subject = authResult.getName(); //主题
        String token = JwtUtil.createToken(subject,now,expireTime); //生成Token
        response.setStatus(ResultEnum.SUCCESS.getCode());
        //返回客户单Token信息
        response.setHeader("Authorization","Bearer " + token);
    }
}
